<?php
namespace app\admin\model;  
use think\Model;
use think\Db;
use think\Session;

class Choice extends model
{
	protected $autoWriteTimestamp = 'datetime';
	protected $error = '';
	protected function initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::initialize();
        //TODO:自定义的初始化
    }

    /*
     * 返回数据列表
     */
    public function getList(){
        $creater = Session::get('id');
        $data = Db::table('choice')->where('creater', $creater)
            ->field("id,title,create_time,update_time,case category when 1 then '单选题' when 2 then '多选题' else '不定项选择题' end as category")
            ->select();
        return $data;
    }
    /*
     * 修改试题的paperid
     */
    public function updatePaperId($data,$paperid){
        if($data){
            $this->error = '';
            $dataarr = explode(',',$data);
            foreach($dataarr as $key=>$value){
                $sdata = Db::table('choice')->where('id',$value)->field('paperid')->find();
                if($sdata['paperid']){
                    $paperids = $sdata['paperid'].','.$paperid;
                }else{
                    $paperids = $paperid;
                }
                $result = Db::table('choice')->where('id', $value)->update(['paperid' =>$paperids]);
                if($result > 0){

                }else{
                    $this->error = '数据更新失败';
                    break;
                }
            }
            if($this->error){
                return false;
            }else{
                return true;
            }
        }
    }

    public function getError(){
        return $this->error;
    }
    /**
     * 返回指定id的信息
     * @param atring $ids
     * $return array
     */
    public function getInfoByIds($ids){
        $data = Db::table('choice')
            ->where('id','in',$ids)
            ->field('id,title,answer,optionA,optionB,optionC,optionD,analysis,score')
            ->select();
        return $data;
    }

    /*
     * 删除试题的paperid
     */
    public function delPaperId($data,$paperid){
        if($data){
            $this->error = '';
            $dataarr = explode(',',$data);
            foreach($dataarr as $key=>$value){
                $sdata = Db::table('choice')->where('id',$value)->field('paperid')->find();
                $sdataarr = explode(',',$sdata['paperid']);

                foreach($sdataarr as $k=>$v){
                    if($paperid == $v){
                        unset($sdataarr[$k]);
                    }
                }
                $paperids = implode(',',$sdataarr);
                $result = Db::table('choice')->where('id', $value)->update(['paperid' =>$paperids]);
                if($result > 0){

                }else{
                    $this->error = '数据更新失败';
                    break;
                }
            }
            if($this->error){
                return false;
            }else{
                return true;
            }
        }
    }

}
